package com.lin.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 加载资源文件并转发到其他页面
 */
public class ServletDemo1 extends HelloServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        try(InputStream resourceAsStream = context.getResourceAsStream("/WEB-INF/classes/db.properties"))
        {
            if (resourceAsStream == null)
            {
                System.out.println("resource not found");
                return;
            }
            Properties properties = new Properties();
            properties.load(resourceAsStream);
            String property = properties.getProperty("username", "lin");
            Object password = properties.getOrDefault("password", "123");
            context.getRequestDispatcher("/hello").forward(req, resp);
            System.out.println(property + password);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
